let cache = require('./cache');

exports.authorize = function(req, res, next) {
    // 校验用户是否登录
    if (req.session === undefined || req.session.user === undefined || req.session.role === undefined) {
        res.json({"success": false, "logged": true, "message": "未登录或登录超时！"});
        return;
    }
    cache.get(req.session.user.id, (err, val) => {
        if (val) {
            if (val !== req.sessionID) {
                req.session.user = null;
                req.session.role = null;
                req.session.destroy();
                res.clearCookie("user");
                res.clearCookie("userId");
                res.clearCookie("sessionId");
                res.clearCookie(global.cookieIndentity);
                delete req.session;
                res.json({"success": false, "logged": true, "message": "您的账号已在其他机器登录！"});
                return;
            }

            next();
        } else {
            res.json({"success": false, "logged": true, "message": "未登录或登录超时！"});
            return;
        }
    });
};